package com.willian.andrappfw.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.core.widget.ContentLoadingProgressBar;

import com.berwin.cocoadialog.CocoaDialog;
import com.berwin.cocoadialog.CocoaDialogStyle;
import com.willian.andrappfw.R;
import com.willian.andrappfw.application.WApplication;
import com.willian.andrappfw.bean.VersionBean;
import com.willian.andrappfw.network.WBaseCallback;
import com.willian.andrappfw.network.WRequest;
import com.willian.andrappfw.network.RequestContext;
import com.willian.andrappfw.network.WApiRetrofit;
import com.willian.andrappfw.network.WBaseResponse;

import java.io.File;
import java.text.MessageFormat;


public class UpdateUtil {
    public static void checkUpdate(ViewGroup viewGroup, RequestContext requestContext, boolean automatic) {
        new WRequest.Builder<WBaseResponse<VersionBean>>()
                .with(requestContext)
                .setObservable(WApiRetrofit.getInstance().versionQuery())
                .setCallback(new WBaseCallback<VersionBean>() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    public void onSucceed(VersionBean data) {
                        if (data == null) {
                            return;
                        }
                        if (data.getPrivateVersion() <= WApplication.ContextHolder.getVersionCode()) {
                            return;
                        }
                        if (automatic && WPreferenceManager.getInstance().getBoolean(PreferenceKeys.NEW_VERSION_ALERT + data.getPrivateVersion(), false)) {
                            return;
                        }
                        WPreferenceManager.getInstance().edit().putBoolean(PreferenceKeys.NEW_VERSION_ALERT + data.getPrivateVersion(), true).apply();
                        AlertDialog d = new AlertDialog.Builder(viewGroup.getContext(), R.style.WAlertDialog)
                                .setTitle(R.string.update_available)
                                .setPositiveButton(R.string.update, (dialog, which) -> {
                                    dialog.dismiss();
                                    downloadAPK(viewGroup, data.getDownloadUrl(), data.getPrivateVersion());
                                })
                                .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss())
                                .show();
                        if (d.getWindow() != null) {
                            WindowManager.LayoutParams params = d.getWindow().getAttributes();
                            params.width = Utils.getScreenWidth() * 3 / 4;
                            d.getWindow().setAttributes(params);
                        }
                        Utils.setAlertDialogButtonTextColor(d, R.color.blue_357CE9, R.color.red_FF2D55);
                    }


                    public void onFailure(Throwable throwable) {
                    }
                })
                .build().enqueue();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void downloadAPK(ViewGroup viewGroup, String url, int versionCode) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ui_update_progress, viewGroup, false);
        ((TextView) view.findViewById(R.id.textView_title)).setText(R.string.downloading);
        ContentLoadingProgressBar progressBar = view.findViewById(R.id.progress);
        TextView progressText = view.findViewById(R.id.textView_progress);
        progressBar.setMax(100);
        progressBar.setMin(0);
        progressBar.setActivated(true);
        progressText.setText("0%");
        CocoaDialog dialog = new CocoaDialog.Builder(viewGroup.getContext(), CocoaDialogStyle.custom).setCustomContentView(view).setCustomWidth(Utils.getScreenWidth() * 3 / 4).build();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnShowListener(dialog1 -> progressBar.setProgress(0));
        dialog.show();

        Utils.downloadFile(url, versionCode + ".apk", new Utils.DownloadListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int currentLength) {
                if (viewGroup.getContext() instanceof Activity) {
                    ((Activity) viewGroup.getContext()).runOnUiThread(() -> progressText.setText(MessageFormat.format("{0}%", currentLength)));
                }
            }

            @Override
            public void onFinish() {
                if (viewGroup.getContext() instanceof Activity) {
                    dialog.dismiss();
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    File apkFile = new File(WApplication.ContextHolder.getContext().getFilesDir() + "/" + versionCode + ".apk");
                    Uri contentUri = FileProvider.getUriForFile(viewGroup.getContext(), "com.supersoco.diagnosis.fileprovider", apkFile);
                    install.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    viewGroup.getContext().startActivity(install);
                }
            }

            @Override
            public void onFailure() {

            }
        });
    }
}
